<template>
    <el-form :model="form" ref="formRef" label-width="120px" style="padding: 20px;">
        <!-- 表单头部 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="出库单号">
                    <el-input v-model="form.outboundnumber" placeholder="可不填写，自动生成" disabled></el-input>
                </el-form-item>
                <el-form-item label="供应商编号" required>
                    <el-input v-model="form.supplierID"></el-input>
                </el-form-item>
                <el-form-item label="供应商联系方式" required>
                    <el-input v-model="form.supplierPhone"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="form.rember" :maxlength="300" placeholder="请输入备注信息"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="出库单类型" prop="storage" required>
                    <el-select v-model.number="form.outbound" placeholder="请选择入库类型">
                        <el-option label="领料出库" :value="101"></el-option>
                        <el-option label="成品出库" :value="102"></el-option>
                        <el-option label="销售出库" :value="103"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商名称" prop="supplierName" required>
                    <el-input v-model="form.supplierName"></el-input>
                </el-form-item>
                <el-form-item label="制单人">
                    <el-input v-model="form.creator" disabled></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="关联订单号" prop="associatedNum">
                    <el-input v-model="form.associatedNum"></el-input>
                </el-form-item>
                <el-form-item label="供应商联系人" prop="supplierPeople">
                    <el-input v-model="form.supplierPeople"></el-input>
                </el-form-item>
                <el-form-item label="制单时间">
                    <el-input v-model="form.outAuditTime" disabled></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <div>
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addopen"
                style="float: right; margin-bottom: 10px;">新增产品</el-button>
        </div>
        <!-- 产品表格 -->
        <el-table :data="products" style="margin-top: 20px;" border>
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column label="产品名称" prop="productName"></el-table-column>
            <el-table-column label="产品编码" prop="productId"></el-table-column>
            <el-table-column label="规格" prop="specification"></el-table-column>
            <el-table-column label="批次" prop="batch"></el-table-column>
            <el-table-column label="单价" prop="price"></el-table-column>
            <el-table-column label="出库数量">
                <template #default="{ row }">
                    <el-input v-model.number="row.quantity" size="small" type="number"
                        @input="calculateTotal(row)"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="总价" width="100">
                <template #default="{ row }">
                    <span :style="row.totalPrice < 0 || isNaN(row.totalPrice) ? 'color: red' : ''">
                        {{ row.totalPrice.toFixed(2) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="库位" prop="location"> </el-table-column>
            <el-table-column label="操作" width="80">
                <template #default="{ row }">
                    <el-button  type="primary" link size="small" icon="el-icon-edit" @click="deleteProduct(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm" style="margin-left: 10px;">返回</el-button>
        </div>
    </el-form>

    <el-dialog v-model="centerDialogVisible" title="选择产品" style="width: 1300px;height: 900px;" center @open="handleDialogOpen">
        <span>
            <el-table :data="productsData" style="width: 100%;" border row-key="productId" ref="productTableRef">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="productId" label="产品ID"></el-table-column>
                <el-table-column prop="productName" label="产品名称"></el-table-column>
                <el-table-column prop="categoryId" label="类别"></el-table-column>
                <el-table-column prop="specification" label="规格"></el-table-column>
                <el-table-column prop="price" label="单价"></el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="demo-pagination-block">
                <el-pagination
                    v-model:current-page="page.pageindex"
                    v-model:page-size="page.pageSize"
                    :page-sizes="[15, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageind.totalcount"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    prev-text="上一页"
                    next-text="下一页"
                />
            </div>
        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addSelectedProducts">添加</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted, nextTick } from 'vue'; // 添加了nextTick导入
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { KongaUrl } from '@/axios/axiosHelp';

const router = useRouter();
const route = useRoute();
const Store = useCounterStore();

// 表单数据
const form = reactive({
    pid: 0,
    outbound: 101,
    outboundnumber: `CP${Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000}`,
    associatedNum: "",
    quantity: "",
    storage: 101,
    supplier: "",
    supplierID: "",
    supplierName: "",
    supplierPeople: "",
    supplierPhone: "",
    creator: Store.user?.userName || '未知用户',
    reviewer: "",
    outAuditTime: new Date().toISOString().substring(0, 10),
    outAuditstatus: 101,
    outCreationTime: new Date().toISOString(),
    rember: "",
    proName: "",
    proId: "",
    specifications: "",
    batch: "",
    unitprice: "",
    uNumber: "",
    price: "",
    binlocation: "",
    isDelete: 0
});

const centerDialogVisible = ref(false);
const productsData = ref([]);
const loading = ref(false);
const productTableRef = ref(null);
const products = ref([]);
const selectedProductIds = ref([]);

const page = reactive({
    ProductNum: "",
    ProductName: "",
    Category: "",
    pageindex: 1,
    pageSize: 15,
});

const pageind = reactive({
    totalpage: 0,
    totalcount: 0,
});

// 计算总价
const calculateTotal = (row) => {
    row.price = parseFloat(row.price) || 0;
    row.quantity = parseFloat(row.quantity) || 0;
    row.totalPrice = row.price * row.quantity;
};

// 加载产品数据
const Moks = async () => {
    loading.value = true;
    try {
        const res = await KongaUrl({
            url: "/activity/api/Peoduct/GetProductsByConditions/paginated",
            method: "get",
            params: {
                ProductNum: page.ProductNum,
                ProductName: page.ProductName,
                Category: page.Category,
                pageindex: page.pageindex,
                pageSize: page.pageSize,
            },
        });
        
        if (res.status === 200) {
            console.log('产品数据',res.data)
            productsData.value = res.data.result.list;
            pageind.totalcount = res.data.result.totalcount;
            pageind.totalpage = res.data.result.totalPage;
        }
    } catch (error) {
        ElMessage.error("加载产品数据失败");
        console.error(error);
    } finally {
        loading.value = false;
    }
};

const handleSizeChange = (val) => {
    page.pageSize = val;
    Moks();
};

const handleCurrentChange = (val) => {
    page.pageindex = val;
    Moks();
};

// 添加选中的产品
const addSelectedProducts = () => {
    if (!productTableRef.value) {
        ElMessage.error("请先搜索产品");
        return;
    }
    
    const selectedRows = productTableRef.value.getSelectionRows();
    if (selectedRows.length === 0) {
        ElMessage.warning("请至少选择一个产品");
        return;
    }
    
    const selectedIds = selectedRows.map(row => row.productId);
    folieShow(selectedIds);
    centerDialogVisible.value = false;
};

// 获取产品详情
const folieShow = async (selectedIds) => {
    try {
        const res = await KongaUrl.get("/activity/api/Peoduct/GetProductModelsByIds/product-ids", {
            params: { productIds: selectedIds },
            paramsSerializer: (params) => {
                return Object.entries(params).flatMap(([key, value]) => {
                    if (Array.isArray(value)) {
                        return value.map(v => `${key}=${encodeURIComponent(v)}`);
                    }
                    return `${key}=${encodeURIComponent(value)}`;
                }).join('&');
            }
        });
        
        products.value = res.data.map(product => ({
            ...product,
            price: product.price || 0,
            quantity: 0,
            totalPrice: 0,
            batch: '',
            location: ''
        }));
    } catch (error) {
        ElMessage.error("获取产品数据失败：" + error.message);
        console.error("接口错误：", error);
    }
};

// 取消表单操作
const cancelForm = () => {
    router.push("/Showout");
};

// 加载出库单数据
const fantian = async () => {
    try {
        const res = await KongaUrl({
            url: '/activity/api/OutManage/GetOutManageById',
            method: 'get',
            params: { id: route.query.id }
        });
        
        if (res.status === 200) {
            const data = res.data;
            
            // 回显基础表单数据
            Object.assign(form, {
                pid: data.pid,
                outbound: data.outbound,
                outboundnumber: data.outboundnumber,
                associatedNum: data.associatedNum,
                supplierID: data.supplierID,
                supplierName: data.supplierName,
                supplierPeople: data.supplierPeople,
                supplierPhone: data.supplierPhone,
                creator: data.outCreator,
                rember: data.rember
            });
            
            // 解析产品数据
            const parseProductData = (str) => {
                return str.replace(/\{|\}/g, '').split(',').map(item => item.trim());
            };
            
            if (data.productId && data.productName && data.specification && 
                data.price && data.quantity && data.batch && data.binlocation) {
                
                const productIds = parseProductData(data.productId);
                const productNames = parseProductData(data.productName);
                const specifications = parseProductData(data.specification);
                const prices = parseProductData(data.price);
                const quantities = parseProductData(data.quantity);
                const batches = parseProductData(data.batch);
                const locations = parseProductData(data.binlocation);
                
                // 存储已选中的产品ID
                selectedProductIds.value = productIds;
                
                // 构建产品数组
                products.value = productIds.map((id, index) => ({
                    productId: id,
                    productName: productNames[index] || '',
                    specification: specifications[index] || '',
                    price: parseFloat(prices[index]) || 0,
                    quantity: parseFloat(quantities[index]) || 0,
                    totalPrice: (parseFloat(prices[index]) || 0) * (parseFloat(quantities[index]) || 0),
                    batch: batches[index] || '',
                    location: locations[index] || ''
                }));
            }
        }
    } catch (error) {
        ElMessage.error('获取出库单数据失败：' + error.message);
        console.error("接口错误：", error);
    }
};

const handleDialogOpen = async () => {
    try {
        // 等待数据加载和DOM准备
        await nextTick();
        
        // 调试信息
        console.log('productTableRef:', productTableRef.value);
        console.log('productsData length:', productsData.value?.length);
        console.log('selectedProductIds:', selectedProductIds.value);
        
        // 确保所有必要条件满足
        if (!productTableRef.value || !productsData.value?.length) {
            console.warn('必要条件未满足，无法处理选中状态');
            return;
        }
        
        // 转换ID为Set以便快速查找
        const selectedIdsSet = new Set(selectedProductIds.value.map(String));
        
        // 清除当前选择
        productTableRef.value.clearSelection();
        
        // 遍历并选中匹配项
        productsData.value.forEach(row => {
            if (selectedIdsSet.has(String(row.productId))) {
                productTableRef.value.toggleRowSelection(row, true);
            }
        });
        
        console.log('产品选中状态处理完成');
    } catch (error) {
        console.error('处理选中状态时出错:', error);
        ElMessage.error('初始化产品选择失败');
    }
};

// 打开新增产品对话框
const addopen = async () => {
    try {
        await Moks(); // 确保产品数据已加载
         // 等待数据加载和DOM更新
    await nextTick(); 
        centerDialogVisible.value = true;
    } catch (error) {
        ElMessage.error('加载产品数据失败');
    }
};

// 删除产品
const deleteProduct = (row) => {
    products.value = products.value.filter(item => item.productId !== row.productId);
    // 同时从已选中的ID列表中移除
    selectedProductIds.value = selectedProductIds.value.filter(id => id !== row.productId);
    ElMessage.success('产品删除成功');
};

// 提交表单
const submitForm = async () => {
    try {
        const submitData = {
            id:route.query.id,
            pid: '1',
            outbound: form.outbound,
            outboundnumber: String(form.outboundnumber),
            associatedNum: form.associatedNum,
            batch: products.value.map(row => `{${row.batch}}`).join(','),
            supplier: "无",
            supplierID: form.supplierID,
            supplierName: form.supplierName,
            supplierPeople: form.supplierPeople,
            supplierPhone: form.supplierPhone,
            outCreator: Store.user?.userName || '未知用户',
            outReviewer: "无",
            outAuditTime: new Date().toISOString(),
            outAuditstatus: 101,
            outCreationTime: new Date().toISOString(),
            rember: form.rember,
            productName: products.value.map(row => `{${row.productName}}`).join(','),
            productId: products.value.map(row => `{${row.productId}}`).join(','),
            specification: products.value.map(row => `{${row.specification}}`).join(','),
            price: products.value.map(row => `{${row.price}}`).join(','),
            quantity: products.value.map(row => `{${row.quantity || ''}}`).join(','),
            totalprice: products.value.map(row => `{${row.totalPrice}}`).join(','),
            binlocation: products.value.map(row => `{${row.location}}`).join(','),
            isDelete: 0,
            shenRember: "无"
        };

        const res = await KongaUrl({
            url: '/activity/api/OutManage/UpdateOutManage',
            method: 'post',
            data: submitData
        });

        if (res.status === 200) {
            ElMessage.success('更新成功');
            router.push('/Showout');
        } else {
            ElMessage.error('更新失败');
        }
    } catch (error) {
        if (error.response) {
            ElMessage.error(`提交请求失败，状态码: ${error.response.status}，错误信息: ${error.response.data}`);
        } else if (error.request) {
            ElMessage.error('提交请求已发送，但没有收到响应');
        } else {
            ElMessage.error('提交请求时发生错误: ' + error.message);
        }
        console.error('接口错误：', error);
    }
};

// 初始化
onMounted(() => {
    Moks();
    if (route.query.id) {
        fantian();
    }
});
</script>

<style scoped>
.el-table {
    width: 100%;
}

.search-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.search-container .el-input {
    flex: 1;
    max-width: 200px;
}

.demo-pagination-block {
    margin-top: 15px;
    text-align: right;
}
</style>